
define(['ionic', 'services'], function () {
    angular.module('U9Mobile.services')
        .factory('FileStorage', ['$q', '$http', '$log', '$cordovaFile', 'UtilService', 'AppConstants',
            function ($q, $http, $log, $cordovaFile, UtilService, AppConstants) {
                var configDefer = $q.defer(),
                    config = {},
                    o = {
                        loadingPromise: configDefer.promise,
                        set: errorHandler,
                        get: errorHandler
                    };

                o.loadingPromise.then(function () {
                    o.set = function (key, value) {
                        var defer = $q.defer();

                        if (angular.isString(key)) {
                            config[key] = value;
                        } else if (angular.isObject(key)) {
                            angular.extend(config, key);
                        }
                        writeConfigFile().then(function () {
                            defer.resolve();
                        }, function () {
                            defer.reject();
                        });

                        return defer.promise;
                    };
                    o.get = function (key, defaults) {
                        return config.hasOwnProperty(key) ? config[key] : (defaults || null);
                    };
                });

                init();

                return o;

                function errorHandler(err) {
                    $log.error("Error", err);
                }

                function init() {
                    if (window.cordova) {
                        initAppFileDir().then(function () {
                            readConfigFile().then(function (jsonData) {
                                angular.extend(config, jsonData);
                                readJumpLandingConfig().then(function () {
                                    configDefer.resolve();
                                }, function () {
                                    configDefer.resolve();
                                });
                            }, function () {
                                configDefer.resolve();
                            });
                        }, function () {
                            configDefer.resolve();
                        });
                    } else {
                        //configDefer.resolve();
                        $http.get(AppConstants.DEBUG_CONFIG_FILE_URL).success(function (jsonData) {
                            angular.extend(config, jsonData);
                            configDefer.resolve();
                        }).error(function () {
                            configDefer.resolve();
                        });
                    }

                }

                function initAppFileDir() {
                    var defer = $q.defer(),
                        externalRootDir = UtilService.getExternalRootDir();
                    $cordovaFile.checkDir(externalRootDir, AppConstants.APP_NAME).then(function () {
                        defer.resolve();
                    }, function () {
                        $cordovaFile.createDir(externalRootDir, AppConstants.APP_NAME, false).finally(function () {
                            defer.resolve();
                        });
                    });

                    return defer.promise;
                }

                function readJumpLandingConfig() {
                    var defer = $q.defer();
                    window.Analytics.analytics("login", "main", function (data) {
                        if (data.hasOwnProperty("account") && data.account.length > 0) {
                            angular.forEach(data, function (value, key) {
                                config[key] = value;
                            });
                            config.autologin = true;
                            writeConfigFile().then(function () {
                                defer.resolve();
                            }, function () {
                                defer.reject();
                            });
                        } else {
                            defer.resolve();
                        }
                    }, function () {
                        defer.reject();
                    });

                    return defer.promise;
                }

                function readConfigFile() {
                    var defer = $q.defer(),
                        configFileDir = UtilService.getConfigDir();
                    $cordovaFile.checkFile(configFileDir, AppConstants.CONFIG_FILE_NAME).then(function () {
                        $cordovaFile.readAsText(configFileDir, AppConstants.CONFIG_FILE_NAME).then(function (data) {
                            defer.resolve(angular.fromJson(data));
                        }, function () {
                            defer.reject();
                        });
                    }, function () {
                        defer.resolve({});
                    });

                    return defer.promise;
                }

                function writeConfigFile() {
                    var defer = $q.defer();

                    if (window.cordova) {
                        $cordovaFile.writeFile(UtilService.getConfigDir(), AppConstants.CONFIG_FILE_NAME, angular.toJson(config), true).then(function () {
                            defer.resolve();
                        }, function () {
                            defer.reject();
                        });
                    } else {
                        defer.resolve();
                    }

                    return defer.promise;
                }
            }
        ]);
});